<template>
    <div v-if="editOpen">
      <t-table :selected-row-keys="selectedRowKeys"
               @select-change="(val)=>{selectedRowKeys=val}" :data="data"
               :columns="columns" rowKey="id">
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
        <template #dateRange="{row}">
          <!--   :disable-date="disableDate" -->
          <t-date-range-picker :status="row.dateRangeStatus" @change="()=>{ if(row.dateRange.length>0){row.dateRangeStatus='default'} }"  v-model="row.dateRange"
                               :placeholder="['开始时间','结束时间']" allow-input clearable>
            <div slot="tips" v-if="row.dateRangeStatus==='error'">不能为空</div>
          </t-date-range-picker>
        </template>
        <template #content="{row}">
          <t-textarea :maxlength="200" @change="()=>{ if(row.content!==''){row.contentStatus='default'} }" :status="row.contentStatus"
                      clearable :autosize="{minRows: 3}" v-model="row.content">
            <div slot="tips" v-if="row.contentStatus==='error'">不能为空</div>
          </t-textarea>
        </template>
        <template #empty>
          <span>暂无数据 请点击新增按钮</span>
        </template>
      </t-table>
      <div style="margin-top: 10px" class="btn-group-inline">
        <t-button @click="addResearchPlan">新增</t-button>
        <!--        <t-button @click="upResearchPlan">上移</t-button>-->
        <!--        <t-button @click="downResearchPlan">下移</t-button>-->
        <t-button @click="delResearchPlan">删除</t-button>
      </div>
    </div>
    <div v-else>
      <t-table :selected-row-keys="selectedRowKeys"
               @select-change="(val)=>{selectedRowKeys=val}" :data="data"
               :columns="columns2" rowKey="id">
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
        <template #dateRange="{row, rowIndex}">
           <span :style="{color:diffData.length>=rowIndex+1 && (diffData[rowIndex].newStartDate!==row.newStartDate || diffData[rowIndex].newEndDate!==row.newEndDate)?'red':''}">
          {{ row.newStartDate }} 至 {{ row.newEndDate }}
           </span>
        </template>
        <template #content="{row, rowIndex}">
           <span :style="{color:diffData.length>=rowIndex+1 && diffData[rowIndex].content!==row.content?'red':''}">
          {{ row.content }}
           </span>
        </template>
      </t-table>
    </div>

</template>

<script>
import dayjs from "dayjs";

export default {
  name: "project-research-plan",
  props: {
    value: Array,
    projectId: [String, Number],
    editOpen: {
      type: Boolean,
      default: false
    },
    phaseType: {
      type: String,
      default: '1'
    },
    oldData: {
      type: Array,
      default: () => [],
    },
    useOldData: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      disableDate: {},
      header: '新增年度研究计划',
      visible: true,
      dialogOpen: false,
      formData: {
        dateRange: [],
        content: ''
      },
      diffData: [],
      rules: {
        dateRange: [{required: true, validator: (val) => val && val.length, message: "起止时间不能为空", type: "error"}],
        content: [
          {
            required: true,
            message: "计划内容不能为空",
            type: "error"
          }
        ],
      },
      selectedRowKeys: [],
      data: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64
        },
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "dateRange",
          title: "起止时间",
          align: "center",
        },
        {
          colKey: "content",
          title: "主要工作内容及阶段目标（每阶段限200字）",
          align: "center",
        },
      ],
      columns2: [
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "dateRange",
          title: "起止时间",
          align: "center",
        },
        {
          colKey: "content",
          title: "主要工作内容及阶段目标",
          align: "center"
        },
      ],
    }
  },
  watch: {
    value: {
      deep: true,
      immediate: true,
      handler(val) {
        if(val && val.length>0 && this.useOldData){
          const newArr = val.map(data=>({
            ...data,
            dateRange: [data.newStartDate, data.newEndDate],
            initType: 'init'
          }))
          // 防止无限循环，简单比较一下
          if (JSON.stringify(val) !== JSON.stringify(this.data)) {
            this.data = newArr
          }
        }
      }
    },
    projectId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getResearchPlan(val);
        }
      }
    },
    data: {
      deep: true,
      immediate: true,
      handler(val) {
        if(val && val.length>0){
          const newData = val.map((val, index) => ({
            ...val,
            sort: index + 1,
            newStartDate: val.dateRange[0],
            newEndDate: val.dateRange[1],
            phaseType: this.phaseType,
            projectId: Number(this.projectId),
          }))
          this.$emit("input", newData);
        }
      }
    },
    oldData: {
      deep: true,
      immediate: true,
      handler(val) {
        this.diffData = this.oldData;
      }
    },
  },
  methods: {
    checkData() {
      const isValidate = this.data.every((val, index) => {
        if (val.dateRange.length <= 0) {
          this.$set(this.data[index], 'dateRangeStatus', 'error')
          this.$message.error(`项目进度：第${index + 1}条起止时间不能为空`);
          return false;
        }
        this.$set(this.data[index], 'dateRangeStatus', 'default')
        if (!val.content) {
          this.$set(this.data[index], 'contentStatus', 'error')
          this.$message.error(`项目进度：第${index + 1}条主要工作内容及阶段目标不能为空`);
          return false;
        }
        this.$set(this.data[index], 'contentStatus', 'default')
        return true;
      });
      return isValidate;
    },
    created(){
      // this.getResearchPlan()
    },
    getResearchPlan() {
      if (!this.projectId){
        return false;
      }
      if(this.phaseType == '1'){
        this.$api.kjxm.project.get(Number(this.projectId)).then(response => {
          this.disableDate = {
            before: dayjs(response.data.newStartDate, "YYYY-MM-DD").endOf('month').subtract(1, 'month').format(),
            after: dayjs(response.data.newEndDate, "YYYY-MM-DD").endOf('month').subtract(0, 'month').format(),
          }
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      }else {
        this.$api.kjxm.contract.getByProject(Number(this.projectId)).then(response => {
          this.disableDate = {
            before: dayjs(response.data.newStartDate, "YYYY-MM-DD").endOf('month').subtract(1, 'month').format(),
            after: dayjs(response.data.completeDate, "YYYY-MM-DD").endOf('month').subtract(0, 'month').format(),
          }
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      }


      // 显示外层带的数据不查询
      if(this.useOldData){
        return false;
      }
      this.$api.kjxm.project.researchPlanGet(Number(this.projectId), this.phaseType).then(response => {
        if (response.data.length <= 0 && this.phaseType !== '1'  && this.editOpen === true) { // 获取不到读申报项目的经费
          let lastStep = Number(this.phaseType) - 1 > 0 ? Number(this.phaseType) - 1 : 1
          if(this.phaseType === '3'){
            lastStep = 1
          }
          this.$api.kjxm.project.researchPlanGet(Number(this.projectId), lastStep).then(response2 => {
            response2.data = response2.data.map((val) => ({
              ...val,
              phaseType: this.phaseType,
              dateRange: [val.newStartDate, val.newEndDate]
            }));
            this.data = response2.data;
            const newData = this.data.map((val, index) => ({...val, sort: index + 1}))
            this.$emit("input",newData)
          }).catch((e) => {
            this.$message.error(e.toString());
          });
        } else {
          response.data = response.data.map((val) => ({
            ...val,
            phaseType: this.phaseType,
            dateRange: [val.newStartDate, val.newEndDate]
          }));
          this.data = response.data;
          const newData = this.data.map((val, index) => ({...val, sort: index + 1}))
          this.$emit("input", newData);
        }
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    addResearchPlan() {
      const newId = Number(new Date().getTime()) + Number(Math.random() * 10)
      this.data.push({
        id: newId,
        dateRange: [],
        content: "",
        phaseType: this.phaseType,
        projectId: this.projectId
      })
    },
    upResearchPlan() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[0].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index - 1)
      }
    },
    downResearchPlan() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index + 1)
      }
    },
    delResearchPlan() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.data.splice(index, 1)
      this.selectedRowKeys = [];
    },
    moveInArray(arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
    onSubmit() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.data.push({
            id: Number(new Date().getTime()) + Number(Math.random() * 10),
            ...this.formData
          })
          this.$refs.form.reset();
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
  }
}
</script>

<style scoped>

</style>
